package com.java.simple.smallmybatis.binding;

import cn.hutool.core.lang.ClassScanner;
import com.java.simple.smallmybatis.session.SqlSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author zhoujunlin
 * @date 2022年12月22日 14:42
 * @desc
 */
public class MapperRegistry {

    /**
     * 将已添加的映射器代理加入到HashMap
     */
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (Objects.isNull(mapperProxyFactory)) {
            throw new RuntimeException("Type " + type + " is not known to be the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new RuntimeException("Error getting mapper instance.", e);
        }
    }

    public <T> void addMapper(Class<T> type) {
        // Mapper必须是接口才会注册
        if (type.isInterface()) {
            if (hasMapper(type)) {
                // 如果重复添加了  报错
                throw new RuntimeException("Type " + type + " is already known to the MapperRegistry.");
            }
            // 注册映射器代理工厂
            knownMappers.put(type, new MapperProxyFactory<>(type));
        }
    }

    public <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }

    public void addMapper(String packageName) {
        Set<Class<?>> mapperSet = ClassScanner.scanPackage(packageName);
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }
    }

}
